package com.kr.aia.powerrp.closing;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.kr.aia.powerrp.common.MainMovieClipListView;
import com.kr.aia.powerrp.common.RecController;
import com.kr.aia.powerrp.common.VideoPlayController;
import com.kr.aia.powerrp.common.commonUtil;
import com.kr.aia.powerrp.common.VideoPlayController.onTestCompletionListener;
import com.kr.aia.powerrp.db.ClosingDBUtil;
import com.kr.aia.powerrp.db.ClosingInfoVO;
import com.kr.aia.powerrp.db.RPGroupDBUtil;
import com.kr.aia.powerrp.db.RPGroupInfoVO;
import com.kr.aia.powerrp.R;

public class ClosingMain extends Activity implements OnClickListener{
	private String dirName;
    private String dataPath;
    
	private commonUtil comUtil;
	
	private ClosingDBUtil closingDataSource;
	private ArrayList<ClosingInfoVO> closingData;
	
    private LinearLayout recorderView;
    private RecController recorderController;
    
    private VideoPlayController videoController;
    private MainMovieClipListView mcv;
    
    private Button closing_btn_home;
    private Button closing_btn_movies;
    private Button closing_btn_save;
    
    private ImageButton closing_btn_record;
    private ImageButton closing_btn_stop;
    
    private Switch closing_title_change_swtich;
    private Switch closing_content_change_swtich;
    private SeekBar closing_seekbar_size;
    
    private EditText closingTextView;
    
    private LinearLayout closing_input_layout_left;
    private LinearLayout closing_input_layout_right;
    
    private LinearLayout closing_input_layout;
    private final int txtNum = 17;
    private EditText[] closing_input_element = new EditText[txtNum];
    private int selectedClosing = -1;
    
    
    @Override
    public void onDestroy(){
    	closingDataSource.close();
    	Log.e("PRP", "DB CLOSED");
    	super.onDestroy();
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.closing_main);
        comUtil = new commonUtil();
        
        
        closingDataSource = new ClosingDBUtil(this);
        closingDataSource.open();
        closingData = closingDataSource.getAllData();
        
        if(closingData == null || closingData.size() < 1){
        	ClosingInfoVO tmpClosingVO = new ClosingInfoVO("새이름", "");
        	
        	for(int i = 0 ; i < txtNum; i++){
        		closingDataSource.insertClosingInfo(tmpClosingVO);
        	}
        	
        	closingData = closingDataSource.getAllData();
        }
        
        
        /*for(int i = 0 ; i < closingData.size() ; i++){
        	Log.e("PRP", "seq : " + closingData.get(i).getSeqno() + "  title: " + closingData.get(i).getTitle() + "  content: " + closingData.get(i).getContent());
        }*/
        
        
        
        // 객체 등록
        closing_btn_home	= (Button) findViewById(R.id.closing_btn_home);
        closing_btn_movies	= (Button) findViewById(R.id.closing_btn_movies);
        closing_btn_save	= (Button) findViewById(R.id.closing_btn_save);
        
        closingTextView		= (EditText) findViewById(R.id.closingTextView);
        //closingTextView.setEnabled(false);
        closingTextView.setFocusableInTouchMode(false);
        
        closing_title_change_swtich		= (Switch) findViewById(R.id.closing_title_change_swtich);
        closing_content_change_swtich	= (Switch) findViewById(R.id.closing_content_change_swtich);
        closing_seekbar_size			= (SeekBar) findViewById(R.id.closing_seekbar_size);
        
        //closing_input_layout_left		= (LinearLayout) findViewById(R.id.closing_input_layout_left);
        //closing_input_layout_right		= (LinearLayout) findViewById(R.id.closing_input_layout_right);
        
        
        for(int i = 0 ; i < txtNum; i ++){
        	int closingTxtId = getResources().getIdentifier("closingText" + (i+1), "id", getPackageName());
        	EditText tmpEditText = (EditText) findViewById(closingTxtId);
        	closing_input_element[i] = tmpEditText;
        	tmpEditText.setBackgroundDrawable(getResources().getDrawable(R.drawable.common_input_border_trans));
        	tmpEditText.setSingleLine(true);
            tmpEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
            tmpEditText.setText(closingData.get(i).getTitle());
            tmpEditText.setTextColor(getResources().getColor(android.R.color.white));
            tmpEditText.setFocusable(false);
            tmpEditText.setCursorVisible(false);
            
            tmpEditText.setOnTouchListener(new closingClickListener());
        }
        
        /*
        LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lParam.setMargins(0,1,0,1);
        LinearLayout.LayoutParams lInputParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lInputParam.setMargins(10, 5, 30, 5);
        LinearLayout.LayoutParams rInputParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rInputParam.setMargins(30, 5, 10, 5);
        
        
        for(int i = 0 ; i < 4 ; i ++){
        	closing_input_layout = new LinearLayout(this);
            closing_input_layout.setGravity(Gravity.CENTER_VERTICAL);
            closing_input_layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.closing_text_bg_left));
            
            EditText tmpEditText = new EditText(this);
            
            tmpEditText.setTextSize(20);
            tmpEditText.setGravity(Gravity.CENTER_VERTICAL);
            tmpEditText.setBackgroundDrawable(getResources().getDrawable(R.drawable.common_input_border_trans));
            tmpEditText.setSingleLine(true);
            tmpEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
            tmpEditText.setText(closingData.get(i).getTitle());
            tmpEditText.setTextColor(getResources().getColor(android.R.color.white));
            tmpEditText.setFocusable(false);
            tmpEditText.setCursorVisible(false);
            tmpEditText.setId(i);
            tmpEditText.setOnTouchListener(new closingClickListener());
            
            closing_input_element[i] = tmpEditText;
            closing_input_layout.addView(tmpEditText, lInputParam);
            closing_input_layout_left.addView(closing_input_layout, lParam);
        }
        
        
        for(int i = 0 ; i < 11 ; i ++){
        	closing_input_layout = new LinearLayout(this);
            closing_input_layout.setGravity(Gravity.CENTER_VERTICAL);
            closing_input_layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.closing_text_bg_right));
            
            EditText tmpEditText = new EditText(this);
            tmpEditText.setTextSize(20);
            tmpEditText.setGravity(Gravity.CENTER_VERTICAL);
            tmpEditText.setBackgroundDrawable(getResources().getDrawable(R.drawable.common_input_border_trans));
            tmpEditText.setSingleLine(true);
            tmpEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
            tmpEditText.setText(closingData.get(i+4).getTitle());
            tmpEditText.setTextColor(getResources().getColor(android.R.color.white));
            tmpEditText.setFocusable(false);
            tmpEditText.setCursorVisible(false);
            tmpEditText.setId(i+4);
            tmpEditText.setOnTouchListener(new closingClickListener());
            
            closing_input_element[i+4] = tmpEditText;
            closing_input_layout.addView(tmpEditText, rInputParam);
            closing_input_layout_right.addView(closing_input_layout, lParam);
        }
        */
        
        
        closing_btn_record = (ImageButton) findViewById(R.id.closing_btn_record);
        closing_btn_stop = (ImageButton) findViewById(R.id.closing_btn_stop);
        comUtil.makeDisabledButton(closing_btn_stop, true);
        
        
        recorderView = (LinearLayout) findViewById(R.id.closing_preview);


        // Video View 
        recorderController = new RecController(this, "closing");
        recorderView.addView(recorderController);
        
        
        
        closing_title_change_swtich.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				// TODO Auto-generated method stub
				boolean on = ((Switch) arg0).isChecked();
	            
	            if (on) {
	            	//recorderView.setVisibility(View.GONE);
	            	for(int i = 0 ; i < txtNum ; i++){
	            		closing_input_element[i].setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.common_input_border));
	            		closing_input_element[i].setTextColor(getResources().getColor(android.R.color.black));
	            		closing_input_element[i].setFocusable(true);
	            		closing_input_element[i].setFocusableInTouchMode(true);
	            		closing_input_element[i].setCursorVisible(true);
	                }
	            } else {
	            	//if(!closing_content_change_swtich.isChecked()){
	            		//recorderView.setVisibility(View.VISIBLE);
	            	//}
	            	for(int i = 0 ; i < txtNum ; i++){
	            		closing_input_element[i].setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.common_input_border_trans));
	            		closing_input_element[i].setTextColor(getResources().getColor(android.R.color.white));
	            		closing_input_element[i].setFocusable(false);
	            		closing_input_element[i].setCursorVisible(false);
	                }
	            }
			}
        });
        
        
        closing_content_change_swtich.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				boolean on = ((Switch) arg0).isChecked();
	            
	            if (on) {
	            	//recorderView.setVisibility(View.GONE);
	            	//closingTextView.setEnabled(true);
	            	closingTextView.setFocusableInTouchMode(true);
	            	closingTextView.setFocusable(true);
	            	closingTextView.setCursorVisible(true);
	            } else {
	            	closingTextView.setFocusable(false);
	            	closingTextView.setCursorVisible(false);
	            	//Toast.makeText(getApplicationContext(), "off",Toast.LENGTH_LONG).show();
	            	//closingTextView.setEnabled(false);
	            }
			}
        });
        
        
        closing_seekbar_size.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {       

		    @Override       
		    public void onStopTrackingTouch(SeekBar seekBar) {      
		        // TODO Auto-generated method stub    
		    	closingTextView.setTextSize((float) (20.0 + (seekBar.getProgress() * 0.2)));
		    }       

		    @Override       
		    public void onStartTrackingTouch(SeekBar seekBar) {     
		        // TODO Auto-generated method stub
		    }
		    
		    @Override       
		    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {     
		        // TODO Auto-generated method stub
		    }
		});
        
        
        
        // 클릭 리스너 등록
        closing_btn_home.setOnClickListener(this);
        closing_btn_movies.setOnClickListener(this);
        closing_btn_save.setOnClickListener(this);
        
        closing_btn_record.setOnClickListener(this);
        closing_btn_stop.setOnClickListener(this);
    }
    
    
    @Override
    public void onClick(View v){
    	switch(v.getId()){
    		case R.id.closing_btn_home:
    			finish();
    			break;
    		case R.id.closing_btn_movies:
    			AlertDialog.Builder builder = new AlertDialog.Builder(this);
    			
    		    mcv = new MainMovieClipListView(this, "closing");
    			View mcvView = mcv.openMovieClipListView();
    			
		   		//.setIcon(R.drawable.icon_sja)		// icon 지정 후 Builder 객체 리턴
    			builder.setTitle("동영상 목록")				// title 지정
		   		//.setMessage("메시지 영역")			// 메시지 text 지정
		   		.setView(mcvView)	// 커스텀 뷰 지정
		   		.setPositiveButton("크게보기", new positiveButtonClickListener())
		   		.setNeutralButton("작게보기", new neutralButtonClickListener())
		   		.setNegativeButton("닫기", new DialogInterface.OnClickListener(){
		   			@Override
					public void onClick(DialogInterface dialog, int which) {
		   				dialog.dismiss();
		   			}
		   		});
    			builder.show(); // 지금까지 설정한 dialog를 화면에 보이고 AlertView객체를 return
    			
    			break;
    		case R.id.closing_btn_save:
    			
    			if(selectedClosing >= 0){
    			
	    			// 화면상의 값을 VO에 저장
	    			for(int i = 0 ; i < txtNum; i++){
	    				closingData.get(i).setTitle(closing_input_element[i].getText().toString());
		        	}
	    			
	    			// 저장된 VO의 값 중에 title을 DB에 저장
	    			for(int i = 0 ; i < closingData.size(); i++){
	    				long aff = closingDataSource.updateClosingTitle(closingData.get(i));
	    				
	    				if(aff < 0){
	    					Toast.makeText(this, "제목 저장 실패.", Toast.LENGTH_LONG).show();
	    					break;
	    				}
		        	}
	    			
	    			// content를 DB에 저장
	    			long resUpdate = closingDataSource.updateClosingContent(selectedClosing, closingTextView.getText().toString());
	    			
	    			
	    			if(resUpdate < 0){
	    				Toast.makeText(this, "내용 저장 실패.", Toast.LENGTH_LONG).show();
	    			}else{
	    				closingData.get(selectedClosing).setContent(closingTextView.getText().toString());
	    				Toast.makeText(this, "저장되었습니다.", Toast.LENGTH_LONG).show();
	    			}
    			}
    			
    			break;
    		case R.id.closing_btn_record:
    			try {
                	recorderController.startRecording();
                	closing_btn_record.setEnabled(false);
                	closing_btn_record.setAlpha(0.2f);
                	
                	closing_btn_stop.setEnabled(true);
                	closing_btn_stop.setAlpha(1.0f);
                } catch (Exception e) {
                    String message = e.getMessage();
                    Log.i(null, "Problem Start"+message);
                    recorderController.releaseMediaRecorder();
                    
                    closing_btn_record.setEnabled(true);
                    closing_btn_record.setAlpha(1.0f);
                	
                    closing_btn_stop.setEnabled(false);
                    closing_btn_stop.setAlpha(0.2f);
                }
    			break;
    		case R.id.closing_btn_stop:
    			try{
    				recorderController.stopRecording();
    			}catch(Exception e){
    				
    			}finally{
    				closing_btn_record.setEnabled(true);
    				closing_btn_record.setAlpha(1.0f);
                	
    				closing_btn_stop.setEnabled(false);
    				closing_btn_stop.setAlpha(0.2f);
    			}
    			break;
    	}
    }
    
    
    public class closingClickListener implements OnTouchListener{

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			EditText view = (EditText) v;
			
			
			for(int i = 0 ; i < txtNum ; i++){
				if(v.getId() == getResources().getIdentifier("closingText" + (i+1), "id", getPackageName())){
					selectedClosing = i;
					break;
				}
			}
			
			closingTextView.setText(closingData.get(selectedClosing).getContent());
			
			
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				view.setAlpha(0.5f);
                break;
            case MotionEvent.ACTION_UP:
            	//view.setColorFilter(0x00FFFFFF);
            	view.setAlpha(1.0f);
                break;
            }
			
			return false;
		}
    }
    
    
    public class positiveButtonClickListener implements DialogInterface.OnClickListener{
    	@Override
		public void onClick(DialogInterface dialog, int which) {
			//dialog.dismiss();
			//Log.e("PRP", "----------------- " + intentUri.toString());
			if(mcv.getIntentUri() != null){
				Intent intent = new Intent();
	            intent.setAction(Intent.ACTION_VIEW);
	            intent.setDataAndType(mcv.getIntentUri(), "video/mp4");
	            startActivity(intent);
			}
		}
	};
	
	public class neutralButtonClickListener implements DialogInterface.OnClickListener{
    	@Override
		public void onClick(DialogInterface dialog, int which) {
    		if(mcv.getIntentUri() != null){
	    		videoController = new VideoPlayController(getApplicationContext(), mcv.getIntentUri().toString());
	    		videoController.setOnCompletionListener(onTestClickListener);
	    		
	    		recorderView.removeView(recorderController);
	    		recorderView.addView(videoController);
    		}
		}
	};
	
	private onTestCompletionListener onTestClickListener = new onTestCompletionListener()
    {
		@Override
		public void onCompletion(MediaPlayer arg0) {
			recorderView.removeView(videoController);
			recorderView.addView(recorderController);
		}
    };
}